package com.quectel.taskserver.job.partybuilding;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.partybuilding.PartyPersonMsgBusiness;
import com.quectel.constant.PushConstants;
import com.quectel.constant.core.mobileuser.MobileUserMsgConstants;
import com.quectel.constant.core.partybuilding.PartyBuildingConstants;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.core.module.partybuilding.dto.PartyPersonBirthdayMsgRecordDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonBirthdayMsgTemplateDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyPersonBirthdayMsgRecordService;
import com.quectel.core.module.partybuilding.service.PartyPersonBirthdayMsgTemplateService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.util.common.DateUtils;
import com.quectel.util.kit.PageFetchKit;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 党建生日祝福消息发送
 *
 * @author: bob
 * @email: bob.yu@quectel.com
 * @date: 2023-06-12 8:59:00
 */
@Component
public class PartyPersonBirthMsgPushTask implements SimpleJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyPersonBirthMsgPushTask.class);

    private static final String TIMT_FORMAT = "HH:mm";
    /**
     * 间隔五分钟
     */
    private static final int TASK_DURATION_MINUTES = 5;

    @DubboReference
    private PartyPersonBirthdayMsgTemplateService birthdayMsgTemplateService;
    @DubboReference
    private PartyPersonBirthdayMsgRecordService birthdayMsgRecordService;
    @DubboReference
    private PartyPersonService partyPersonService;
    @DubboReference
    private MobileUserService mobileUserService;

    @Autowired
    private PartyPersonMsgBusiness partyPersonMsgBusiness;

    @Override
    public void execute(ShardingContext shardingContext) {
        generatePartyBuildingMeetingMsg();
    }

    /**
     * 1.先查询规则
     * 2.根据规则租户id 查询租户下的党员列表
     */
    private void generatePartyBuildingMeetingMsg() {
        LOGGER.info("党员祝福消息推送，开始执行... 时间 {} 下面各个机器开始抢占执行", DateUtils.getCurrentDateStr(DateUtils.FormatType.COMMON));

        int currentYear = Year.now().getValue();

        List<PartyPersonBirthdayMsgTemplateDto> templateDtos = birthdayMsgTemplateService.queryList(new HashMap<>());
        if (CollectionUtils.isEmpty(templateDtos)){
            LOGGER.error("没有找到祝福模板");
            return;
        }

        for (PartyPersonBirthdayMsgTemplateDto msgTemplateDto: templateDtos) {
            Long tenantId = msgTemplateDto.getTenantId();

            // 判断当前租户规则是否该执行
            String pushTime = msgTemplateDto.getPushTime();

            DateTime nowDateTime = DateUtil.parse(DateUtil.format(new Date(), TIMT_FORMAT), TIMT_FORMAT);
            DateTime pushDateTime = DateUtil.parse(pushTime, TIMT_FORMAT);
            // 比较时间

            if (DateUtil.between(nowDateTime, pushDateTime, DateUnit.MINUTE, true) < (TASK_DURATION_MINUTES * 2)) {
                // 最早提前10分钟 最晚延后10分钟

                // 查询租户下出今天生日的人
                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put(LambdaUtil.getFieldName(PartyPersonDto::getTenantId), tenantId);
                queryMap.put(LambdaUtil.getFieldName(PartyPersonDto::getProbationTime), DateUtil.today().substring(5));

                List<PartyPersonDto> result = PageFetchKit.fetchAll(reqParams -> partyPersonService.queryList(reqParams), queryMap);

                if (CollectionUtils.isEmpty(result)) {
                    LOGGER.error("没有找到党员信息");
                    break;
                }

                // 真正需要发送的人
                List<PartyPersonDto> needSendPersonList = new ArrayList();
                // 查询看是否有已发送的记录
                for (PartyPersonDto personDto : result) {
                    PartyPersonBirthdayMsgRecordDto dbRecord = birthdayMsgRecordService.selectOne(personDto.getId(), String.valueOf(DateUtil.thisYear()));
                    if (dbRecord == null){
                        needSendPersonList.add(personDto);
                    }
                }

                // 过滤下认证过的人
                List<MobileUserDto> sendUserList = getSendUserList(needSendPersonList);

                for (MobileUserDto mobileUser : sendUserList) {
                    List<MobileUserDto> mobileList = new ArrayList<>();
                    mobileList.add(mobileUser);

                    PartyPersonDto personDto = partyPersonService.selectOne(tenantId, mobileUser.getMobile());
                    // 拼装发送消息内容
                    String name = personDto.getName();
                    String joinDate = DateUtil.formatDate(personDto.getProbationTime());
                    long partyAge = DateUtil.betweenYear(personDto.getProbationTime(), new Date(), true);
                    String formatMsg = msgTemplateDto.getRemark().replaceAll("\\[@姓名\\]", name)
                            .replaceAll("\\[@入党日期\\]", joinDate)
                            .replaceAll("\\[@党龄\\]", String.valueOf(partyAge));

                    String formatTitle = msgTemplateDto.getTitle().replaceAll("\\[@姓名\\]", name)
                            .replaceAll("\\[@入党日期\\]", joinDate)
                            .replaceAll("\\[@党龄\\]", String.valueOf(partyAge));

                    MobileUserMsgConstants.SourceType meetingSourceType = MobileUserMsgConstants.SourceType.PARTY_PERSON_BIRTH_MSG;

                    PartyPersonBirthdayMsgRecordDto addly = new PartyPersonBirthdayMsgRecordDto();
                    addly.setTenantId(personDto.getTenantId());
                    addly.setPartyId(personDto.getPartyId());
                    addly.setTemplateId(msgTemplateDto.getId());
                    addly.setYear(String.valueOf(currentYear));
                    addly.setPersonId(personDto.getId());
                    addly.setTitle(formatTitle);
                    addly.setRemark(formatMsg);
                    addly.setCreateTime(new Date());
                    Long recordId = birthdayMsgRecordService.save(addly);

                    partyPersonMsgBusiness.pushMsg(
                            personDto.getTenantId(),
                            mobileList,
                            meetingSourceType,
                            recordId,
                            String.format(PartyBuildingConstants.PUSH_PARTY_BIRTH_MSG_TITLE, MobileUserMsgConstants.SourceType.PARTY_PERSON_BIRTH_MSG.getDefaultTitle()),
                            String.format(PartyBuildingConstants.PUSH_PARTY_BIRTH_MSG_CONTENT, formatTitle),
                            true,
                            new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                    );

                }
            }
        }


        LOGGER.info("党员祝福消息推送执行结束");
    }

    public static void main(String[] args) {
        String string = "&lt;p&gt;亲爱的[@姓名]党员朋友：&lt;/p&gt;&lt;p&gt;从[@入党日期]日当，直到今天您已入党[@党龄]年！&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;在这特殊而值得庆祝的日子里，我谨代表党组织向您送上最诚挚的生日祝福！&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;作为一名党员，您是党的坚强力量，是为人民奋斗的先锋。在党的旗帜下，您始终秉持着信仰和使命，无私地为党和人民事业贡献着自己的力量。&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;您以无私奉献的精神，默默地为党和人民做出了许多贡献。您以自己的实际行动践行着党的宗旨，为实现共产主义的崇高目标而努力奋斗。&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;在您的生日这一天，让我们一同为您庆祝，感谢您对党的事业的无私奉献和坚定信仰。您的热情和付出是我们共同前进的动力和力量源泉。&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;愿您的生日充满欢乐和温馨，愿您的人生之路一直洒满阳光。在新的一岁里，愿您继续保持初心，不忘党员身份，用实际行动为党和人民做出更大贡献。&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;衷心祝愿您生日快乐！愿您健康、幸福，愿您的梦想和理想在党的指引下不断实现！&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;再次祝福您生日快乐！&lt;/p&gt;&lt;p style=&quot;text-align: start;&quot;&gt;最诚挚的祝福！&lt;/p&gt;";

        String name = "李四";
        String joinDate = "2014-01-01";
        int partyAge = 9;
        String formattedMessage = string.replaceAll("\\[@姓名\\]", name)
                .replaceAll("\\[@入党日期\\]", joinDate)
                .replaceAll("\\[@党龄\\]", String.valueOf(partyAge));
        System.out.println(formattedMessage);
    }

    // 获取发送用户列表,过滤掉没有认证过的人，因为推不出去消息
    private List<MobileUserDto> getSendUserList(List<PartyPersonDto> partyPersonList) {
        return partyPersonList.stream()
                .map(PartyPersonDto::getMobile)
                .map(mobileUserService::selectByMobile)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
